package logic

import (
	"context"
	"ewaimai/waimairpc/cache"
	"ewaimai/waimairpc/models"
	"fmt"

	"ewaimai/waimairpc/internal/svc"
	"ewaimai/waimairpc/waimairpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsCarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsCarAddLogic {
	return &GoodsCarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsCarAddLogic) GoodsCarAdd(in *waimairpc.GoodsCarAddRequest) (*waimairpc.GoodsCarAddResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var u models.User
	u.ID = uint(in.UserId)
	if err = u.GetUserById(int(in.UserId)); err != nil {
		logx.Errorf("用户不存在")
	}
	var g models.Goods
	if err = g.GetGoods(int(in.GoodsId)); err != nil {
		logx.Error("商品不存在")
	}
	if cache.IsExisit(int(in.UserId), int(in.GoodsId)) {
		fmt.Println("购物车存在该商品")
		cache.UpdateCar(int(in.UserId), int(in.GoodsId), int(in.Num))
		logx.Errorf("累加失败")
		goodsMap := map[string]interface{}{
			"name":    in.Name,
			"price":   in.Price,
			"num":     in.Num,
			"status":  1,
			"userId":  in.UserId,
			"goodsId": in.GoodsId,
		}
		if err = cache.CartAdd(int(in.UserId), int(in.GoodsId), goodsMap); err != nil {
			logx.Errorf("购物车添加失败")
		}
	}

	return &waimairpc.GoodsCarAddResponse{
		Id: int64(g.ID),
	}, nil
}
